﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MtApi;
using MTEA.WatchDog;

namespace MTEA
{
    class MTWorker
    {
        private static string Tag = "MTWorker";
        private MTStatusDisplay display;
        private MtApiClient client;
        private Experter experter;
        public void Start()
        {
            client = new MtApiClient();
            experter = new Experter(client, "GOLD");
            client.ConnectionStateChanged += Client_ConnectionStateChanged;
            client.QuoteUpdated += Client_QuoteUpdated;
            display = new MTStatusDisplay(client);
            
            client.BeginConnect(8222);
        }

        private void Client_QuoteUpdated(object sender, string symbol, double bid, double ask)
        {
            MTLogcat.i(Tag,string.Format("{0} Bid:{1} Ask:{2}",symbol,bid,ask));
            experter.Tick();
            //var order = client.GetOrder(54988553, OrderSelectMode.SELECT_BY_TICKET, OrderSelectSource.MODE_TRADES);
            //Console.WriteLine(order.Profit);
            return;
        }

        private void Disconnect()
        {
            client.BeginDisconnect();
        }
        private void OrderSendBuy()
        {
            int tickId=client.OrderSendBuy("GOLD", 1, 1);
            Console.WriteLine("OrderSendBuy successfully tickId : "+tickId);
        }
        private void OrderSendSell()
        {
            int tickId = client.OrderSendSell("GOLD", 1, 1);
            Console.WriteLine("OrderSendSell successfully tickId : " + tickId);
        }

        private void OrderClose()
        {
            int tickId = Convert.ToInt32(Console.ReadLine());
            bool result=client.OrderClose(tickId, 1);
            Console.WriteLine("OrderClose {0} {1}",tickId,result);
        }
        private void Client_ConnectionStateChanged(object sender, MtConnectionEventArgs e)
        {
            if (e.Status == MtConnectionState.Connected)
            {
                //display.DisplayOrders();
                //display.DisplayHistoryOrders();
                MTWatchDog.Instance.Start();
            }
        }


        public void ExcCommand(int cmd)
        {
            switch (cmd)
            {
                case 0:
                    Disconnect();
                    break;
                case 1:
                    OrderSendBuy();
                    break;
                case 2:
                    OrderSendSell();
                    break;
                case 3:
                    OrderClose();
                    break;
                case 4:
                    display.DisplayOrders();
                    break;
            }
        }
    }
}
